package com.example.mediaplay;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {
	private IMediaPlayer mp;
	private SurfaceView sv;
	private ServiceConnection conn = new MediaPlayerServiceConnection();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		sv = (SurfaceView)this.findViewById(R.id.surfaceView1);
		
		Intent service = new Intent(this,MediaPlayerService.class);
		bindService(service, conn, BIND_AUTO_CREATE);
		
		sv.getHolder().setFixedSize(300, 300);
		sv.getHolder().setKeepScreenOn(true);
		sv.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		sv.getHolder().addCallback(new SurfaceViewHolderCallback());
		
	}
	
	public void playClick(View v){
		mp.setPath(getPath());
		mp.play();
	}
	

	
	@Override
	protected void onDestroy() {
		unbindService(conn);
		super.onDestroy();
	}

	public void pauseClick(View v){
		mp.pause();
	}
	
	public void stopClick(View v){
		mp.stop();
	}
	
	private String getPath(){
		EditText pathText = (EditText)this.findViewById(R.id.path);
		return pathText.getText().toString();
	}
	
	
	private final class MediaPlayerServiceConnection implements ServiceConnection{

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mp = (IMediaPlayer)service;
			mp.setSurfaceHolder(sv.getHolder());
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}
		
	}
	
	private final class SurfaceViewHolderCallback implements Callback{

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			mp.play();
		}

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			mp.pause();
		}
		
	}


}
